package com.vonchenchen.usbmuxd_android.usbmuxd.localconn.sharemem;

import android.os.MemoryFile;
import android.os.ParcelFileDescriptor;
import android.util.Log;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by lidechen on 3/28/17.
 */

public class AshmemDistributer extends AshmemConnector {

    private final String TAG = "AshmemDistributer";

    private String mPort;

    private MemoryFile mMemoryFile = null;

    public AshmemDistributer(int port, int size){

        mPort = port+"";
        try {
            mMemoryFile = new MemoryFile("AshmemService",size);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public ParcelFileDescriptor getParcelFileDescriptor(){
        return mFd;
    }

    @Override
    public void open() throws IOException {

        Class clz = mMemoryFile.getClass();
        try {
            FileDescriptor fd = null;
            Method getParceFileDescriptor = clz.getMethod("getFileDescriptor");
            fd = (FileDescriptor) getParceFileDescriptor.invoke(mMemoryFile);
            if(fd != null){
                Log.d(TAG, "getFileDescriptor: fd" + fd);

                Class clzp = ParcelFileDescriptor.class;
                Constructor c = clzp.getDeclaredConstructor(fd.getClass());
                mFd = (ParcelFileDescriptor) c.newInstance(fd);
                Log.d(TAG, "getFileDescriptor: pfd" + mFd.getFd());
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

        mSocketInput = new FileInputStream(mFd.getFileDescriptor());
        mSocketOutput = new FileOutputStream(mFd.getFileDescriptor());
    }

    @Override
    public void close() throws IOException {

    }
}
